<script setup lang="ts">
import { MsgType, PrescriptionStatus } from '@/enum'
import type { Picture } from '@/types/consult'
import type { Message, Prescription } from '@/types/room'
import { showImagePreview, showToast } from 'vant'
import { onUpdated } from 'vue'
// import { timeOptions, illnessedOptions } from '@/common'
import { useUserStore } from '@/stores'
// import dayjs from 'dayjs'
import EvaluateCard from './EvaluateCard.vue'
import { useRouter } from 'vue-router'
import { useFormat, useShowPrescription } from '@/composable'
defineProps<{
  list: Message[]
  initChat: boolean
}>()

const store = useUserStore()

// 图片预览
const previewImg = (pics?: Picture[]) => {
  // 如果是空则提示没有图片可以预览，有则进行预览
  if (pics) {
    if (!pics.length) return showToast('没有图片可预览')
    showImagePreview(pics.map((item) => item.url))
  }
}
/* // 进行数据的转换 --- 患病时间和是否就诊过，vue3中没有过滤器，可以使用函数
const getIllnessTime = (val?: number) => {
  return timeOptions.find((item) => item.value === val)?.label
}
const getIllnessFlag = (val?: number) => {
  return illnessedOptions.find((item) => item.value === val)?.label
}
// 格式化时间 -- 创建订单时间 HH:ss
const formatTime = (time: string) => {
  return dayjs(time).format('HH:ss')
} */
const { formatTime, getIllnessFlag, getIllnessTime } = useFormat()
// 图片加载完成
const loadSuccess = (flag: boolean) => {
  // 如果不是发送图片的情况，则不需要进行滚动到底部
  if (flag) {
    console.log(flag, 'imgFlag')
    window.scrollTo(0, document.body.scrollHeight)
  }
}
onUpdated(() => {
  let images = document.querySelectorAll(
    '.van-image__img'
    // eslint-disable-next-line no-undef
  ) as NodeListOf<HTMLImageElement>
  let imgArr: Array<string> = []
  // 获取所有图片地址
  images.forEach((img) => {
    imgArr.push(img.src)
  })
  // 给所有图片添加点击预览的功能
  images.forEach((img, index) => {
    img.addEventListener('click', () => {
      showImagePreview({
        images: imgArr,
        startPosition: index
      })
    })
  })
})
// 获取处方单
const { showPrescription } = useShowPrescription()
/* const getPrescription = async (id?: string) => {
  if (id) {
    showPrescription(id)
    const data = await getPrescriptionUrl(id)
    showImagePreview([data.data.url])
  }
} */
// 购买药品
// 1. 创建了订单但是没有支付的情况，跳转到药品待支付的页面
// 2. 已经支付的情况，跳转到订单详情页面
// 3. 没有创建订单也没有支付，跳转到支付页面
const router = useRouter()
// const roomId = inject<Ref<string>>('roomId')
const buy = (prescription?: Prescription) => {
  console.log(prescription, 'prescription')
  if (prescription?.status === PrescriptionStatus.Invalid)
    return showToast('药品无效')
  else if (
    prescription?.status === PrescriptionStatus.NotPayment &&
    !prescription.orderId
  ) {
    // 这里的id为处方id
    return router.push('/order/pay?id=' + prescription.id)
  }
  // 这里id为订单id
  router.push(`/order/${prescription?.orderId}`)
}
</script>

<template>
  <div
    class="room-message-page"
    v-for="{
      msgType,
      msg,
      id,
      from,
      createTime,
      fromAvatar,
      imageFlag
    } in list"
    :key="id"
  >
    <!-- 患者详情 -->
    <div class="patient-card" v-if="msgType === MsgType.CardPat">
      <div class="patient-info">
        <p class="user">
          {{ msg.consultRecord?.patientInfo.name }}
          {{ msg.consultRecord?.patientInfo.genderValue }} 18岁
        </p>
        <p class="flag">
          {{ getIllnessTime(msg.consultRecord?.illnessTime) }} |
          {{ getIllnessFlag(msg.consultRecord?.consultFlag) }}
        </p>
      </div>
      <van-row>
        <van-col span="6">病情描述</van-col>
        <van-col span="18">{{ msg.consultRecord?.illnessDesc }}</van-col>
        <van-col span="6">图片</van-col>
        <van-col span="18" @click="previewImg(msg.consultRecord?.pictures)"
          >点击查看</van-col
        >
      </van-row>
    </div>
    <!-- 等候提示和时间样式一样 -->
    <div class="time-card" v-if="msgType === MsgType.Notify">
      <div class="content">
        <span>{{ msg.content }}</span>
      </div>
    </div>
    <!-- 温馨提示 -->
    <div class="time-card" v-if="msgType === MsgType.NotifyTip">
      <div class="content">
        <span class="tip">温馨提示：</span>
        <span>{{ msg.content }}</span>
      </div>
    </div>
    <!-- 接收信息 文字-->
    <div
      class="message-card"
      v-if="msgType === MsgType.MsgText && from !== store.user?.id"
    >
      <div class="ava">
        <img :src="fromAvatar" alt="" />
      </div>
      <div class="msg">
        <p class="time">{{ formatTime(createTime) }}</p>
        <p class="content">{{ msg?.content }}</p>
      </div>
    </div>
    <!-- 接收消息 图片 -->
    <div
      class="message-card"
      v-if="msgType === MsgType.MsgImage && from !== store.user?.id"
    >
      <div class="ava">
        <img :src="fromAvatar" alt="" />
      </div>
      <div class="msg">
        <p class="time">{{ formatTime(createTime) }}</p>
        <van-image
          @load="loadSuccess(imageFlag)"
          :src="msg.picture?.url"
          width="120"
          radius="10"
        ></van-image>
      </div>
    </div>
    <!-- 发送信息 文字-->
    <div
      class="message-card send-card"
      v-if="msgType === MsgType.MsgText && from === store.user?.id"
    >
      <div class="ava">
        <img :src="fromAvatar" alt="" />
      </div>
      <div class="msg send">
        <p class="time">{{ formatTime(createTime) }}</p>
        <p class="content">{{ msg?.content }}</p>
        <!-- <span class="status">已读</span> -->
      </div>
    </div>
    <!-- 发送信息 图片-->
    <div
      class="message-card send-card"
      v-if="msgType === MsgType.MsgImage && from === store.user?.id"
    >
      <div class="ava">
        <img :src="fromAvatar" alt="" />
      </div>
      <div class="msg send">
        <p class="time">{{ formatTime(createTime) }}</p>
        <van-image
          @load="loadSuccess(imageFlag)"
          :src="msg.picture?.url"
          width="120"
          radius="10"
        ></van-image>
      </div>
    </div>
    <!-- 电子处方 -->
    <div class="recipe-card" v-if="msgType === MsgType.CardPre">
      <div class="content">
        <div class="recipe-header">
          <div class="pre-header">
            <h4>电子处方</h4>
            <span @click="showPrescription(msg.prescription?.id)"
              >原始处方<van-icon name="arrow"
            /></span>
          </div>
          <p>
            {{ msg.prescription?.name }} {{ msg.prescription?.genderValue }}
            {{ msg.prescription?.age }}岁 {{ msg.prescription?.diagnosis }}
          </p>
          <p>开方时间：{{ msg.prescription?.createTime }}</p>
        </div>
        <div class="recipe-body">
          <div
            class="body-item"
            v-for="item in msg.prescription?.medicines"
            :key="item.id"
          >
            <div class="durg">
              <p>{{ item.name }}</p>
              <p>{{ item.usageDosag }}</p>
            </div>
            <div class="num">x{{ item.quantity }}</div>
          </div>
        </div>
      </div>
      <div class="recipe-foot" @click="buy(msg.prescription)">
        <span>购买药品</span>
      </div>
    </div>
    <!-- 关闭诊室 -->
    <div class="close-card time-card" v-if="msgType === MsgType.NotifyCancel">
      <div class="content">
        <span>医生关闭诊室</span>
      </div>
    </div>
    <!-- 医生服务评价 -->
    <evaluate-card
      v-if="msgType === MsgType.CardEva || msgType === MsgType.CardEvaForm"
      :evalute="msg.evaluateDoc"
    ></evaluate-card>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/room.scss';
</style>
